package la.renzhen.rtpt.config.source.template;

import la.renzhen.rtpt.config.source.template.interceptor.GenericRequestHeaderInterceptor;
import lombok.Data;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 单节点处理 <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 23/05/2018 9:46 AM
 */
@Data
public class SingleRestTemplateSelector implements RestTemplateSelector {

    String url;
    String username;
    String password;
    String authorization;
    Map<String, String> header;

    public SingleRestTemplateSelector() {
    }

    public SingleRestTemplateSelector(String url, String username, String password, String authorization, Map<String, String> header) {
        this.url = url;
        this.username = username;
        this.password = password;
        this.authorization = authorization;
        this.header = header;
    }

    @Override
    public RestTemplate init() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout((60 * 1000 * 3) + 5000);
        RestTemplate template = new RestTemplate(requestFactory);

        Map<String, String> headers = headers();
        if (!headers.isEmpty()) {
            template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(new GenericRequestHeaderInterceptor(headers)));
        }
        return template;
    }

    protected Map<String, String> headers() {
        Map<String, String> headers = new HashMap<>(Optional.ofNullable(header).orElse(new HashMap<>()));
        if (password != null) {
            byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
            headers.put("Authorization", "Basic " + new String(token));
        } else if (authorization != null) {
            headers.put("Authorization", authorization);
        }
        return headers;
    }

    @Override
    public String select(RestTemplate template) {
        return url;
    }
}